package blazingbubble.network.game.strategy;

import blazingbubble.game.Game;
import blazingbubble.game.Player;
import moltencore.network.protocol.PlayerJoinedGame;
import org.apache.log4j.Logger;
import spark.network.protocol.Acknowledgement;
import spark.network.protocol.Response;
import spark.network.strategy.IProtocolHandleStrategy;
import spark.network.protocol.Base;
import spark.utility.OutWrapper;

import java.util.Collection;

public class PlayerJoinedGameStrategy implements IProtocolHandleStrategy<PlayerJoinedGame> {
	private Logger logger = Logger.getLogger(PlayerJoinedGameStrategy.class);

	private Game game;
	private IPlayerTeamJoinListener playerTeamJoinListener;
	private PlayerTeamJoinBuffer playerTeamJoinBuffer;

	public PlayerJoinedGameStrategy(Game game, IPlayerTeamJoinListener playerTeamJoinListener, PlayerTeamJoinBuffer playerTeamJoinBuffer) {
		this.game = game;
		this.playerTeamJoinListener = playerTeamJoinListener;
		this.playerTeamJoinBuffer = playerTeamJoinBuffer;
	}

	@Override
	public void handle(PlayerJoinedGame packet, OutWrapper<Response> acknowledgement, Collection<Base> additionalData) {
		Player player = new Player(packet.getPlayerData().getName(), packet.getPlayerData().getClientId());
		player.setBubbleSetId(packet.getPlayerData().getBubbleSetId());
		game.addPlayer(player);
		PlayerTeamJoinBuffer.BufferedJoin bufferedJoin = playerTeamJoinBuffer.remove(player.getClientId());
		if(bufferedJoin != null) {
			player.setTeamIndex(bufferedJoin.getTeamIndex());
			player.setPositionIndex(bufferedJoin.getSlotIndex());
			playerTeamJoinListener.playerJoinedTeam(player);
		}
		acknowledgement.value = new Acknowledgement(packet);
	}
}
